<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Cck\ArticlesSystem\Http\Models\Article;
use Cck\ArticlesSystem\Http\Resources\ArticleResource;
use Cck\ArticlesSystem\Http\Requests\ArticleStoreRequest;
use Cck\ArticlesSystem\Http\Requests\ArticleUpdateRequest;

class ArticlesController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = (int)max($request->query('page_size', 15), 10);
        $page = (int)max($request->query('page', 1), 1);

        $tags = $request->query('tags', []);

        $articles = Article::query()
            ->when($request->query('category_id'), function ($q, $categoryId) {
                $q->where('category_id', $categoryId);
            })
            ->when(is_array($tags) && $tags, function ($q) use ($tags) {
                /** @var Builder $q */
                $q->whereHas('taggables', function ($_) use ($tags) {
                    /** @var Builder $_ */
                    $_->whereIn('tag_id', $tags);
                });
            })
            ->when($request->query('creator_id'), function ($q, $creatorId) {
                $q->where('creator_id', $creatorId);
            })
            ->when($request->has('recommend'), function ($q) use ($request) {
                $q->where('recommend', (boolean)$request->query('recommend'));
            })
            ->when($request->has('verify_status'), function ($q) use ($request) {
                $q->where('verify_status', $request->query('verify_status'));
            })
            ->when($request->has('order_by') || $request->has('order_type'), function ($q) use ($request) {
                if ($request->get('order_type', 'latest') === 'latest') {
                    return $q->latest($request->get('order_by', 'published_at'));
                }

                return $q->oldest($request->get('order_by', 'published_at'));
            }, function ($q) {
                $q->latest('published_at');
            })
            ->withoutGlobalScope('published')
            // ->when(
            //     $request->has('deleted'),
            //     function ($q) use ($request) {
            //         /** @var Builder $q */
            //         if ($request->has('deleted') && $request->get('deleted') !== '') {
            //             $request->get('deleted') ? $q->whereNotNull('deleted_at') : $q->whereNull('deleted_at');
            //         }
            //     },
            //     function ($q) {
            //         $q->whereNotNull('deleted_at');
            //     }
            // )
            ->when($request->get('published_at') && is_array($request->get('published_at')), function ($q) use ($request) {
                /** @var Builder $q */
                $publishedAt = $request->get('published_at');
                $q->whereBetween('published_at', [$publishedAt['start'], $publishedAt['end'] ?? now()->toDateTimeString()]);
            })
            ->when($request->query('keyword'), function ($q, $keyword) {
                $q->where('title', 'like', '%' . $keyword . '%');
            })
            ->with($this->getWith())
            ->paginate($pageSize, ['*'], 'page', $page);

        return ArticleResource::collection($articles);
    }

    public function show($article)
    {
        $article = Article::query()->withoutGlobalScopes()->findOrFail($article);

        $article->load($this->getWith());

        return new ArticleResource($article);
    }

    public function store(ArticleStoreRequest $request)
    {
        $data = $request->validated();

        $data['creator_id'] = auth()->id();

        /** @var Article $article */
        $article = Article::query()->create($data);

        $data['tags'] && $article->tags()->attach($data['tags']);

        return new ArticleResource($article);
    }

    public function update($article, ArticleUpdateRequest $request)
    {
        $article = Article::query()->withoutGlobalScopes()->findOrFail($article);

        $data = $request->validated();

        $article->update($data);

        isset($data['tags']) && $article->tags()->sync($data['tags']);

        return ['status' => true];
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (!is_array($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        $ids = array_filter(array_unique(array_map('intval', $ids)));

        if (!count($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        \DB::beginTransaction();

        $count = Article::query()->whereIn('id', $ids)->delete();

        if (count($ids) !== $count) {
            \DB::rollBack();

            return ['status' => false, 'message' => '删除失败'];
        }

        \DB::commit();

        return ['status' => true];
    }
}
